package com.huawei;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.eip.v3.EipClient;
import com.huaweicloud.sdk.eip.v3.model.AssociatePublicipsOption;
import com.huaweicloud.sdk.eip.v3.model.AssociatePublicipsRequest;
import com.huaweicloud.sdk.eip.v3.model.AssociatePublicipsRequestBody;
import com.huaweicloud.sdk.eip.v3.model.AssociatePublicipsResponse;
import com.huaweicloud.sdk.eip.v3.region.EipRegion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @description 调用前请根据实际情况替换如下变量：
 * {YOUR AK}，{YOUR SK}，{REGION_ID}，{PUBLICIP ID}，{INSTANCE ID}
 * 绑定实例类型目前支持：PORT、NATGW、VPN、ELB，枚举类型为：AssociateInstanceTypeEnum
 */
public class AssociateInstanceDemo {

    private static final Logger logger = LoggerFactory.getLogger(AssociateInstanceDemo.class);

    public static void main(String[] args) {
        String ak = "{YOUR AK}";
        String sk = "{YOUR SK}";

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        EipClient client = EipClient.newBuilder()
                .withCredential(auth)
                .withRegion(EipRegion.valueOf("{REGION_ID}"))
                .build();

        try {
            AssociatePublicipsResponse response = client.associatePublicips(getRequest());
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            logger.info(e.toString());
        } catch (RequestTimeoutException e) {
            logger.info(e.toString());
        } catch (ServiceResponseException e) {
            logger.info(e.toString());
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
    }

    public static AssociatePublicipsRequest getRequest() {
        AssociatePublicipsRequest request = new AssociatePublicipsRequest();
        request.withPublicipId("{PUBLICIP ID}");
        AssociatePublicipsRequestBody requestBody = new AssociatePublicipsRequestBody();
        AssociatePublicipsOption publicipBody = new AssociatePublicipsOption();
        publicipBody.withAssociateInstanceId("{INSTANCE ID}");
        publicipBody.withAssociateInstanceType(AssociatePublicipsOption.AssociateInstanceTypeEnum.PORT);

        requestBody.withPublicip(publicipBody);
        request.withBody(requestBody);

        return request;
    }
}
